package com.hissagetest;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

public class HelloLayoutSetting extends Activity {
	private static final String spinnerStr[] = {"WrapContent", "MatchParent"} ;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.layout_test_setting);
        
        for (int i = 0; i < 4; i++) {
			_initSettintData(i) ;
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
	        for (int i = 0; i < 4; i++) {
				_saveSettintData(i) ;
			}
		}
			
		return super.onKeyDown(keyCode, event);
	}
	
	private final void _initSettintData(int index) {
		
		int spinnerId = 0 ;
		int editorId  = 0 ;
		
		if (index == 0) {
			spinnerId = R.id.spinner1 ;
			editorId  = R.id.editText1 ;
		} else if (index == 1) {
			spinnerId = R.id.spinner2 ;
			editorId  = R.id.editText2 ;
		} else if (index == 2) {
			spinnerId = R.id.spinner3 ;
			editorId  = R.id.editText3 ;
		} else {
			spinnerId = R.id.spinner4 ;
			editorId  = R.id.editText4 ;
		}
		
		HelloLayoutSettingData.SettingData data = HelloLayoutSettingData.GetData(index) ;
		
		Spinner spinner = (Spinner)findViewById(spinnerId) ;
		EditText editor = (EditText)findViewById(editorId) ;
		
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, spinnerStr);
		
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		
		spinner.setAdapter(adapter);
		
		spinner.setSelection((data.type == ViewGroup.LayoutParams.WRAP_CONTENT) ? 0 : 1) ;
		
		editor.setText(String.format("%d", data.weight)) ;
	}
	
	private final void _saveSettintData(int index) {
		int spinnerId = 0 ;
		int editorId  = 0 ;
		
		if (index == 0) {
			spinnerId = R.id.spinner1 ;
			editorId  = R.id.editText1 ;
		} else if (index == 1) {
			spinnerId = R.id.spinner2 ;
			editorId  = R.id.editText2 ;
		} else if (index == 2) {
			spinnerId = R.id.spinner3 ;
			editorId  = R.id.editText3 ;
		} else {
			spinnerId = R.id.spinner4 ;
			editorId  = R.id.editText4 ;
		}
		
		HelloLayoutSettingData.SettingData data = new HelloLayoutSettingData.SettingData() ;
		
		Spinner spinner = (Spinner)findViewById(spinnerId) ;
		EditText editor = (EditText)findViewById(editorId) ;
		
		data.type = (spinner.getSelectedItemPosition() == 0) ? ViewGroup.LayoutParams.WRAP_CONTENT : ViewGroup.LayoutParams.MATCH_PARENT ;
		
		data.weight = Integer.parseInt(editor.getText().toString()) ;
		
		HelloLayoutSettingData.SetData(index, data) ;
	}
}
